package com.example.shiyanwu; // 请确保与AndroidManifest.xml中的包名一致

import androidx.appcompat.app.AppCompatActivity;
import android.content.Context; // 新增导入
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    // 共享参数文件名
    public static final String PREFERENCE_NAME = "SaveSetting";
    // 组件声明
    private Button btnLogin;
    private EditText etAccount, etPassword;
    private SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化组件
        btnLogin = findViewById(R.id.btn_login);
        etAccount = findViewById(R.id.account_input);
        etPassword = findViewById(R.id.password_input);
        btnLogin.setOnClickListener(this);

        // 初始化SharedPreferences（使用Context.MODE_PRIVATE）
        sp = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        // 加载历史数据
        loadData();
    }

    /** 从SharedPreferences加载数据 */
    private void loadData() {
        String account = sp.getString("account", "");
        String password = sp.getString("password", "");
        etAccount.setText(account);
        etPassword.setText(password);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_login) {
            saveData();
        }
    }

    /** 保存数据到SharedPreferences */
    private void saveData() {
        String account = etAccount.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        if (account.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show();
            return;
        }

        SharedPreferences.Editor editor = sp.edit();
        editor.putString("account", account);
        editor.putString("password", password);
        editor.apply();

        Toast.makeText(this, "登录成功，数据已保存", Toast.LENGTH_SHORT).show();
    }
}